import sys
import io
import os
import json
import subprocess
import requests

# print("系统默认编码:", sys.getdefaultencoding())  # 应显示 'utf-8'

# 强制全局使用 UTF-8 编码
sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='ignore')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

# 设置 Node.js 环境变量（关键！）
os.environ["PYTHONIOENCODING"] = "utf-8"


def get_token_data(data, url):
    try:
        import execjs

        # 直接加载原始文件（需确保不依赖 ES6+ 语法）
        with open('testx.js', 'rb') as f:
            js_code = f.read().decode('utf-8')

        ctx = execjs.compile(js_code)
        return ctx.call("getTokenData", data, url)

    except Exception as e:
        print(f"执行 JavaScript 失败: {e}")
        return None


def loginAction(Cookie, encryptValue, openId, unionId):
    url = 'https://xcx.xybsyw.com/login/login.action'
    data = {
        'username': '15776379355',
        'password': '430ebf279e3521cc1e80055f3db8e4fc',
        'openId': openId,
        'unionId': unionId,
        'model': 'iPhone <iPhone15,4>',
        'brand': 'iPhone',
        'platform': 'ios',
        'system': 'iOS 17.6.1',
        'deviceId': ''
    }

    # 调用 Node.js 获取 token_data
    token_data = get_token_data(data, url)
    if not token_data:
        return

    print("----------", token_data)

    headers = {
        'Host': 'xcx.xybsyw.com',
        'Connection': 'keep-alive',
        'wechat': '1',
        't': token_data['tstr'],
        'Cookie': Cookie,
        'content-type': 'application/x-www-form-urlencoded',
        'encryptValue': encryptValue,
        'm': token_data['md5'],
        'v': '1.6.36',
        'n': 'content,deviceName,keyWord,blogBody,blogTitle,getType,responsibilities,street,text,reason,searchvalue,key,answers,leaveReason,personRemark,selfAppraisal,imgUrl,wxname,deviceId,avatarTempPath,file,file,model,brand,system,deviceId,platform,code,openId,unionid,clockDeviceToken,clockDevice,address,name,enterpriseEmail,responsibilities,practiceTarget,guardianName,guardianPhone,practiceDays,linkman,enterpriseName,companyIntroduction,accommodationStreet,accommodationLongitude,accommodationLatitude,internshipDestination,specialStatement,enterpriseStreet,insuranceName,insuranceFinancing,policyNumber,overtimeRemark,riskStatement,specialStatement',
        's': token_data['iArrStr'],
        'Accept-Encoding': 'gzip,compress,br,deflate',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.56(0x18003838) NetType/WIFI Language/zh_CN',
        'Referer': 'https://servicewechat.com/wx9f1c2e0bbc10673c/477/page-frame.html'
    }

    try:
        response = requests.post(url, headers=headers, data=data)
        response.raise_for_status()
        print(response.text)
    except requests.exceptions.HTTPError as http_err:
        print(f'HTTP 错误: {http_err}')
    except requests.exceptions.RequestException as req_err:
        print(f'请求错误: {req_err}')

# 示例调用
# loginAction('your_cookie', 'your_encryptValue', 'your_openId', 'your_unionId')
